import { Card as SemiCard, ButtonGroup, Button, List } from "@douyinfe/semi-ui";
import { IconRefresh, IconDelete, IconPlusCircle, IconEdit } from "@douyinfe/semi-icons";
import { useEffect } from "react";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { Row, Col, Popconfirm, Space, Descriptions, Table, message, Tooltip } from "antd";
import { EyeOutlined, ApartmentOutlined, TableOutlined } from "@ant-design/icons";

import useHelperInstitution from "../helper/useHelperInstitution";

import useAllInstitutions from "../hooks/institution/useAllInstitutions";
import useDeleteInstitution from "../hooks/institution/useDeleteInstitution";
import useInstitutionPositions from "../hooks/institution/useInstitutionPositions";
import useInstitutionDepartments from "../hooks/institution/useInstitutionDepartments";
import useInstitutionDeletePosition from "../hooks/institution/useDeletePosition";

import InstitutionPositions from "../components/institution/InstitutionPositions";

const oiType = "分支机构";

const BranchPage = () => {
    const { windowInnerHeight } = useModel("global");
    const { openAddBranchInstitutionModal } = useHelperInstitution();

    const { loading, institutions, loadAllInstitutions } = useAllInstitutions(oiType);

    const state = useReactive({
        loading: false,
        currentBranch: {},
        horizontal: false,

        loading: false,
        departments: [],

        currentInstitution: {},
        currentOperate: "分支机构详情",
        showType: "table",
    });

    useEffect(() => {
        let currentBranch = institutions.find((item) => item.oiUuid === state.currentBranch?.oiUuid);
        !currentBranch && institutions.length > 0 && (currentBranch = institutions[0]);
        state.currentBranch = currentBranch || {};
    }, [institutions]);

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={5}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>{oiType}列表</span>}
                        headerStyle={{ padding: "7px 12px" }}
                        headerExtraContent={
                            <ButtonGroup>
                                <Button icon={<IconPlusCircle />} onClick={() => openAddBranchInstitutionModal({ oiType, reloadData: loadAllInstitutions })}></Button>
                                <Button icon={<IconRefresh />} onClick={loadAllInstitutions}></Button>
                            </ButtonGroup>
                        }
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto", textAlign: "center" }}
                    >
                        <List
                            loading={loading}
                            dataSource={institutions}
                            renderItem={(item) => (
                                <List.Item
                                    className={`list-item ${state.currentBranch?.oiUuid === item?.oiUuid ? "list-item-selected" : ""}`}
                                    style={{ padding: "12px 12px 12px 24px" }}
                                    main={item?.oiName}
                                    onClick={() => (state.currentBranch = item)}
                                ></List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={19}>{state.currentBranch?.oiUuid && <BranchDetail {...state} currentBranch={state.currentBranch} reloadData={loadAllInstitutions} />}</Col>
            </Row>
        </div>
    );
};

const BranchDetail = ({ currentBranch, showType, currentOperate, reloadData }) => {
    const { windowInnerHeight } = useModel("global");
    const { openEditBranchInstitutionModal, openAddInstitutionPositionModal, openAddBranchInstitutionDepartmentModal } = useHelperInstitution();
    const { loading, loadInstitutionPositions, positions } = useInstitutionPositions(currentBranch.oiUuid);
    const { loading: dpLoading, loadInstitutionDepartments, departments } = useInstitutionDepartments(currentBranch.oiUuid, "职能部门");
    const { deleteInstitution } = useDeleteInstitution();

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <Row gutter={10}>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}>{currentOperate}</span>}
                    headerStyle={{ padding: "7px 12px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 10, height: cardBodyHeight }}
                    headerExtraContent={
                        <Space>
                            <ButtonGroup className="bnts">
                                <Button
                                    title="编辑当前分支机构信息"
                                    icon={<IconEdit />}
                                    onClick={() => openEditBranchInstitutionModal({ institution: currentBranch, reloadData })}
                                />
                                <Popconfirm title={`确认要删除该分支机构信息吗？`} onConfirm={() => deleteInstitution(currentBranch.oiUuid, reloadData)}>
                                    <Button title="删除当前分支机构" icon={<IconDelete style={{ color: "#E91E63" }} />}></Button>
                                </Popconfirm>
                            </ButtonGroup>

                            <ButtonGroup>
                                <Button
                                    icon={<IconPlusCircle />}
                                    title="添加分支机构岗位成员"
                                    onClick={() =>
                                        openAddInstitutionPositionModal({
                                            institution: currentBranch,
                                            institutionPositions: positions,
                                            reloadData: loadInstitutionPositions,
                                        })
                                    }
                                />
                                <Button title="重新加载分支机构岗位信息" icon={<IconRefresh />} onClick={loadInstitutionPositions}></Button>
                            </ButtonGroup>
                        </Space>
                    }
                >
                    <Descriptions size="small" bordered column={1} style={{ padding: 0 }} labelStyle={{ color: "#999", width: 120, textAlign: "left" }}>
                        <Descriptions.Item label="分支机构名称">{currentBranch.oiName}</Descriptions.Item>
                        <Descriptions.Item label="联系电话">{currentBranch.oiPhon || "-"}</Descriptions.Item>
                        <Descriptions.Item label="负责人">{currentBranch.maInfo?.osName || "-"}</Descriptions.Item>
                        <Descriptions.Item label="管理人">{currentBranch.asInfo?.osName || "-"}</Descriptions.Item>
                        <Descriptions.Item label="所在地区">{currentBranch.oiZoja?.map((item) => item.text).join("") || "-"}</Descriptions.Item>
                        <Descriptions.Item label="详细地址">{currentBranch.oiAddr || "-"}</Descriptions.Item>
                        <Descriptions.Item label="地图经纬度">
                            <Space size={30}>
                                <div>经度：{currentBranch.mpInfo?.radius || "-"}</div>
                                <div>纬度：{currentBranch.mpInfo?.latitude || "-"}</div>
                            </Space>
                        </Descriptions.Item>
                        <Descriptions.Item label="职能说明">{currentBranch.oiDesc || "-"}</Descriptions.Item>
                        <Descriptions.Item label="创建信息">
                            {currentBranch.crInfo?.name} - {currentBranch.crInfo?.time ? formatUTCTime(currentBranch.crInfo.time) : ""}
                        </Descriptions.Item>
                        <Descriptions.Item label="更新信息">
                            {currentBranch.upInfo?.name} - {currentBranch.upInfo?.time ? formatUTCTime(currentBranch.upInfo.time) : ""}
                        </Descriptions.Item>
                    </Descriptions>

                    <div style={{ height: 10 }}></div>

                    <InstitutionPositions loading={loading} positions={positions} reloadData={loadInstitutionPositions} />
                </SemiCard>
            </Col>
            <Col span={16}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}>{currentBranch.oiName} - 部门列表</span>}
                    headerStyle={{ padding: "7px 12px" }}
                    headerExtraContent={
                        <Space>
                            <ButtonGroup>
                                <Button icon={<TableOutlined />} theme={showType === "table" ? "solid" : "light"} onClick={() => (showType = "table")} />
                                {/* <Button title="当前分支机构全景" icon={<ApartmentOutlined />} theme={showType === "tree" ? "solid" : "light"} onClick={() => (showType = "tree")} /> */}
                            </ButtonGroup>

                            <ButtonGroup>
                                <Button
                                    icon={<IconPlusCircle />}
                                    title="添加新分支机构部门"
                                    onClick={() =>
                                        openAddBranchInstitutionDepartmentModal({
                                            institution: currentBranch,
                                            reloadData: loadInstitutionDepartments,
                                        })
                                    }
                                />
                                <Button icon={<IconRefresh />} onClick={loadInstitutionDepartments}></Button>
                            </ButtonGroup>
                        </Space>
                    }
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
                >
                    <DepartmentTable loading={dpLoading} institutions={departments} cardBodyHeight={cardBodyHeight} reloadData={loadInstitutionDepartments} />
                </SemiCard>
            </Col>
        </Row>
    );
};

const DepartmentTable = ({ loading, institutions, cardBodyHeight, reloadData }) => {
    const { openEditBranchInstitutionDepartmentModal, openAddInstitutionPositionModal } = useHelperInstitution();
    const { deleteInstitution } = useDeleteInstitution();

    const renderDesc = (_, r, i) =>
        _ ? (
            <Tooltip title={_}>
                <EyeOutlined />
            </Tooltip>
        ) : (
            "-"
        );

    const renderPositions = (_, r, i) => (
        <ButtonGroup>
            <Button>{_?.length || 0}</Button>
            <Button
                icon={<IconPlusCircle />}
                onClick={() =>
                    openAddInstitutionPositionModal({
                        institution: r,
                        institutionPositions: r.members,
                        reloadData,
                    })
                }
            ></Button>
        </ButtonGroup>
    );

    const renderOperate = (_, r, i) => (
        <ButtonGroup>
            <Button theme="borderless" onClick={() => openEditBranchInstitutionDepartmentModal({ department: r, reloadData })}>
                编辑
            </Button>
            {r?.members?.length === 0 && (
                <Popconfirm
                    title="确认要删除该机构信息吗？"
                    okButtonProps={{ loading: false }}
                    onConfirm={async () => {
                        let res = await deleteInstitution(r.oiUuid);
                        if (res) {
                            message.success("成功删除机构信息");
                            reloadData();
                        }
                    }}
                >
                    <Button theme="borderless" style={{ color: "#f50" }}>
                        删除
                    </Button>
                </Popconfirm>
            )}
        </ButtonGroup>
    );

    const expandable = {
        expandedRowRender: (r) => <DepartmentPositions positions={r.members} reloadData={reloadData} />,
    };

    return (
        <Table loading={loading} bordered dataSource={institutions} rowKey={"id"} pagination={false} expandable={expandable} scroll={{ y: cardBodyHeight }}>
            <Table.Column title="序号" width={70} align="center" render={(_, r, i) => i + 1} />
            <Table.Column title="部门名称" dataIndex={"oiName"} />
            <Table.Column title="部门负责人" dataIndex={"maInfo"} width={120} render={(_, r, i) => _?.osName || "-"} />
            <Table.Column title="职责说明" dataIndex={"oiDesc"} align="center" width={100} render={renderDesc} />
            <Table.Column title="在岗人数" dataIndex={"members"} align="center" width={100} render={renderPositions} />
            <Table.Column title="创建日期" dataIndex={"crInfo"} width={140} render={(_, r, i) => (_?.time ? formatUTCTime(_.time, "YYYY年MM月DD日") : "-")} />
            <Table.Column title="操作" width={140} render={renderOperate} />
        </Table>
    );
};

const DepartmentPositions = ({ positions, reloadData }) => {
    const { deleteInstitutionPosition } = useInstitutionDeletePosition();

    const renderOperate = (_, r, i) => (
        <ButtonGroup>
            <Popconfirm
                title="确认要删除该岗位信息吗？"
                okButtonProps={{ loading: false }}
                onConfirm={async () => {
                    let res = await deleteInstitutionPosition(r.reUuid);
                    if (res) {
                        message.success("成功移除岗位信息");
                        reloadData();
                    }
                }}
            >
                <Button theme="borderless" style={{ color: "#f50" }}>
                    移除
                </Button>
            </Popconfirm>
        </ButtonGroup>
    );

    return (
        <Table bordered dataSource={positions} rowKey={"id"} size="small" pagination={false} style={{ margin: "10px 0" }}>
            <Table.Column title="序号" width={69} align="center" render={(_, r, i) => i + 1} />
            <Table.Column title="姓名" dataIndex={"osName"} />
            <Table.Column title="岗位" dataIndex={"opName"} />
            <Table.Column title="操作" width={80} render={renderOperate} />
        </Table>
    );
};

export default BranchPage;
